const { Controller } = require("egg");

class UserController extends Controller {
    /**
     * 添加用户
     */
    async create() {
        // 解构参数
        const { nickname, mobile, did, email = "" } = this.ctx.request.body;
        // 非空校验
        if (!nickname || !mobile || !did) {
            this.ctx.body = {
                code: 400,
                message: "缺少必须参数",
            };
            return;
        }
        // 查询该手机号是否已注册
        const user = await this.service.user.findByMobile(mobile);
        // 存在，无法再添加
        if (user) {
            this.ctx.body = {
                code: 403,
                message: "该手机号已注册",
            };
            return;
        }
        // 保存该用户
        const res = await this.service.user.createUser({
            nickname,
            mobile,
            did,
            email,
            rid: 2,
        });
        // 添加失败
        if (res.affectedRows !== 1) {
            this.ctx.body = {
                code: 500,
                message: "用户添加失败",
            };
            return;
        }
        // 添加成功
        this.ctx.body = {
            code: 201,
            message: "用户添加成功",
        };
    }

    /**
     * 获取用户列表
     */
    async index() {
        const { rid, did } = this.ctx.query;
        // 如果传入角色 id，直接根据角色 id 获取用户列表
        if (rid) {
            let res = await this.service.user.getUserListByRid(rid);
            this.ctx.body = {
                code: 200,
                data: res,
                message: "请求成功",
            };
            return;
        }
        // 如果传入部门 id，直接根据部门 id 获取用户列表
        if (did) {
            let res = await this.service.user.getUserListByDid(did);
            this.ctx.body = {
                code: 200,
                data: res,
                message: "请求成功",
            };
            return;
        }
        this.ctx.body = {
            code: 200,
            message: "请求成功",
        };
    }

    /**
     * 删除用户
     */
    async delete() {
        const { ids } = this.ctx.query;
        let res = await this.service.user.removeUserList(ids);
        if (res.affectedRows === 0) {
            this.ctx.body = {
                code: 500,
                message: "删除失败",
            };
            return;
        }
        // 删除成功
        this.ctx.body = {
            code: 204,
            message: "删除成功",
        };
    }
}

module.exports = UserController;
